﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Security.Cryptography;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using WordServices.HttpService;

// The Content Dialog item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238

namespace WordsOfLove.ForumPages
{
	public sealed partial class LoginDialog : ContentDialog
	{
		public LoginDialog()
		{
			this.InitializeComponent();
			LoadInfo();
		}

		bool remember;
		string rpwd; 

		private void LoadInfo()
		{
			try
			{
				FileStream file = new FileStream("acccount.data", FileMode.Open);
				StreamReader reader = new StreamReader(file);
				string name = reader.ReadLine();
				rpwd = reader.ReadLine();
				remember = true;
				PasswordBox.Password = "********";
				reader.Close();
				file.Close();
			}
			catch 
			{
				remember = false;
			}
		}

		private void SaveInfo()
		{
			try
			{
				FileStream file = new FileStream("acccount.data", FileMode.OpenOrCreate);
				StreamWriter writer = new StreamWriter(file);
				writer.WriteLine(UserNameBox.Text);
				writer.WriteLine(Md5Encoder.Encode(PasswordBox.Password));
				writer.Close();
				file.Close();
			}
			catch
			{
				remember = false;
			}
		}

		private void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
		{
			HttpUtils utils = HttpUtilsFactory.Utils;
			try
			{
				SaveInfo();
				CurrentUserFactory.CurrentUser =
					utils.SendGetJsonMessage<User>($"api/User/Validate?username={UserNameBox.Text}&password={(remember ? rpwd : Md5Encoder.Encode(PasswordBox.Password))}");
				if(CurrentUserFactory.CurrentUser == null)
				{
					new MessageDialog("用户名或密码错误").ShowAsync();
					args.Cancel = true;
				}
			}
			catch //(Exception ex)
			{
				new MessageDialog("服务器错误").ShowAsync();
				args.Cancel = true;
			}
		}

		private async void RegisterBtn_Click(object sender, RoutedEventArgs e)
		{
			RegisterDialog dialog = new RegisterDialog();
			this.Hide();
			await dialog.ShowAsync();
		}

		private void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
		{
			if (remember)
			{
				PasswordBox.Password = "";
				remember = false;
			}
		}
	}
}
